$NG.AllReady(function (
  page,
  { useDataIndexChange, useValuesChange, useClick, useBeforeClick, useUpdateRows, useUpdateRow }
) {
  if (page.oType == "add") {
    cntMFilter()
  }
  const mstform = $NG.getCmpApi("p_form_unforeseeable_yf_m");
  const dgir1 = $NG.getCmpApi("p_form_unforeseeable_yf_d1");
  const dgir2 = $NG.getCmpApi("p_form_unforeseeable_yf_d2");
  const billno = $NG.getCmpApi("p_form_unforeseeable_yf_m").getItem("bill_no").getValue();
  console.log("获取到数据", billno);

  // getCntCount("p_form_unforeseeable_yf_m","u_main_cnt",()=>{
  //     getCntInfo();
  //     getZbdAmtByCnt()
  //     getFbyfAmtInfo()
  // })
  function setTitle() {
    const cnt_name = (String(mstform.getItem("u_main_cnt").getText()) || 0)
    const dt = (String(mstform.getItem("u_apply_dt").getValue()) || 0)
    $NG.updateState((updater) => {
      updater.data.p_form_unforeseeable_yf_m.setProps({
        bill_name: `${cnt_name}${dt}不可预见分包应付单`
      })
    })
  }


  if (page.oType == 'add') {
    $NG.updateState((updater) => {
      updater.data.p_form_unforeseeable_yf_m.setProps({
        phid_fcur: {
          label: "人民币",
          value: 1,
        },
        exchangerate: 1,
        u_fbhtyfk: 0,
        u_fbljkpje: 0,
        u_main_cnt_ykpje: 0,
        u_bckpje: 0
      });
    });
  }
  //隐藏表头、表体单据引用    
  // $NG.getCmpApi("toolbar_top").getItem('imp').setHidden();
  // const gridToolbar = $NG.getCmpApi("toolbar_p_form_unforeseeable_yf_d1")
  // gridToolbar.getItem('imp').setProps({children:'引用分包结算单'})
  // $NG.getCmpApi("toolbar_p_form_unforeseeable_yf_d2").getItem('imp').setHidden();

  async function getToken() {
    const token = await $NG.request.post({
			url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/authenticationFi",
      header: {
        "Content-Type": "application/json",
      },
    });
    console.log("获取 token 成功:", token);
    return token;
  }

  async function getEventCode() {
    const eventCode = await $NG.request.post({
			url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/getCGEventCode",
      // url: "https://inner-apisix.hisense.com/sd/sd/Fi/sdToFi/fiIntegration/getEventCode?user_key=pxgy9hyt9udfgfcsbzizykw0xfqi6uk6",
      data: JSON.stringify({ bill_no: billno }),
      header: {
        "Content-Type": "application/json",
      },
    });
    console.log("获取 eventCode 成功:", eventCode);
    return eventCode;
  }
  //添加按钮
  $NG.getCmpApi("toolbar_p_form_unforeseeable_yf_d2").insert({
    id: "sendBtn",
    text: "获取发票信息",
    iconCls: "icon-New",
  });
	useClick(async function ({ args }) {
		// console.log("点击了获取发票信息按钮");
		// $NG.getCmpApi("toolbar_top").getItem("save").getRef().click(); //点击获取发票的时候，保存单据
		const identifytype = billno; // 页面唯一标识（根据实际需求设置）
		const token = await getToken();
		const eventCode = await getEventCode();

		// 修正 WebSocket URL
		const socketUrl = "wss://fi-uat.hisense.com/ierp/msgwatch/";

		// 初始化 WebSocket
		const socket = new WebSocket(
			`${socketUrl}?identifytype=${encodeURIComponent(
				identifytype
			)}&token=${encodeURIComponent(token)}&listenerType=RimWebSocketListener`
		);

		// WebSocket 打开事件
		socket.onopen = () => {
			// console.log("WebSocket 连接已建立:", new Date());
			var url = "https://fi-uat.hisense.com/ierp/";
			var viewfpUrl =
				url + "index.html?formId=rim_fpzs_main&eventCode=" + eventCode;
			var encodeUrl = encodeURIComponent(viewfpUrl, "utf-8");
			var requestUrl =
				url +
				"accessTokenLogin.do?encode=true&access_token=" +
				token +
				"&redirect=" +
				encodeUrl;
			window.open(requestUrl);
			socket.send("来自客户端的消息: " + location.href + " - " + new Date());
		};

		// WebSocket 收到消息事件
		socket.onmessage = (event) => {
			// console.log("收到服务器消息:", event.data); // 输出服务器返回的消息
			const data = JSON.parse(event.data);
			const invoiceData = data.invoiceData;

			// 获取表体当前的所有行数据
			const existingRows = $NG
				.getCmpApi("p_form_invoice_information")
				.getRows();

			// 创建一个Set，用于快速判断表体中是否存在某发票号
			const existingInvoiceNos = new Set(
				existingRows.map((row) => row.u_invoiceno)
			);

			// 定义存储新数据的数组
			var gridArr = [];

			// 判断 invoiceData 是否存在，并获取长度
			const gridCount = invoiceData ? invoiceData.length : 0;
			if (gridCount > 0) {
				for (let i = 0; i < gridCount; i++) {
					const invoice = invoiceData[i];
					const invoice_item = invoice.items[0];

					// 判断发票号是否已存在于表体中
					if (existingInvoiceNos.has(invoice.invoiceNo)) {
						continue; // 跳过重复数据
					}

					// 如果发票号未重复，则加入到gridArr中
					var gridObj = {
						u_invoicetype: invoice.invoiceType,
						u_serialno: invoice.serialNo,
						u_invoicecode: invoice.invoiceCode,
						u_invoiceno: invoice.invoiceNo,
						u_invoicedate: invoice.invoiceDate,
						u_checkcode: invoice.checkCode,
						u_salername: invoice.salerName,
						u_salertaxno: invoice.salerTaxNo,
						u_saleraddressphone: invoice.salerAddressPhone,
						u_saleraccount: invoice.salerAccount,
						u_buyername: invoice.buyerName,
						u_buyertaxNo: invoice.buyerTaxNo,
						u_buyeraddressPhone: invoice.buyerAddressPhone,
						u_buyeraccount: invoice.buyerAccount,
						u_invoiceamount: invoice.invoiceAmount,
						u_totaltaxamount: invoice.totalTaxAmount,
						u_totalamount: invoice.totalAmount,
						u_remark: invoice.remark,
						u_machineno: invoice.machineNo,
						u_drawer: invoice.drawer,
						u_reviewer: invoice.reviewer,
						u_payee: invoice.payee,
						u_invoicestatus: invoice.invoiceStatus,
						u_expendstatus: invoice.expendStatus,
						u_billcreatetime: invoice.billCreateTime,
						u_checkstatus: invoice.checkStatus,
						u_invaliddate: invoice.invalidDate,
						u_type: invoice.type,
						u_originalinvoicecode: invoice.originalInvoiceCode,
						u_originalinvoiceno: invoice.originalInvoiceNo,
						u_downloadurl: invoice.downloadUrl,
						u_filetype: invoice.fileType,
						u_isrevise: invoice.isRevise,
						u_snapshoturl: invoice.snapshotUrl,
						u_errcode: invoice.errcode,
						u_description: invoice.description,
						u_validatemessage: invoice.validateMessage,
						u_msg: invoice.msg,
						u_name: invoice.name,
						u_configType: invoice.configType,
						u_config: invoice.config,
						u_key: invoice.key,
						u_taxrate: invoice_item.taxRate,
						u_goodscode: invoice_item.u_goodscode,
						u_goodsname: invoice_item.goodsName,
					};
					gridArr.push(gridObj);
				}

				// 如果有新数据，插入到表体中
				if (gridArr.length > 0) {
					dgrid1.addRows(gridArr);
					// console.log("新增的数据:", gridArr);
				} else {
					// console.log("没有需要插入的新数据。");
				}
			} else {
				// console.log("没有发票数据！");
			}
		};

		// WebSocket 关闭事件
		socket.onclose = (event) => {
			// console.log("WebSocket 连接已关闭:", new Date());
			if (event.code !== 1000) {
				// 非正常关闭
				console.error(
					"连接异常关闭，错误代码:",
					event.code,
					"原因:",
					event.reason
				);
			}
		};

		// WebSocket 错误事件
		socket.onerror = (error) => {
			console.error("WebSocket 错误:", error);
		};

		// 防止内存泄漏，组件卸载时关闭 WebSocket
		return () => {
			if (socket.readyState === WebSocket.OPEN) {
				socket.close();
			}
		};
	}, "sendBtn");

  if (page.oType == "add") {
    $NG.updateState((updater) => {
      updater.data.p_form_unforeseeable_yf_m.setProps({
        u_apply_dt: formatDate(new Date(), "yyyy-mm-dd"),
      });
    });
  }
  const oneTable = $NG.getCmpApi("p_form_unforeseeable_yf_m");

  useValuesChange(({ args }) => {
    console.log(`监听的项目选择`, args);
    const id = args[0].phid_pc?.phid_pc ? args[0].phid_pc?.pc_no : "";
    console.log(`项目id`, id);
    // 通过项目id获取项目信息
    getProjectInfo();
    // 过滤合同
    cntMFilter();
    getCntCount("p_form_unforeseeable_yf_m", "u_main_cnt", () => {
      getCntInfo();
      getZbdAmtByCnt()
      getFbyfAmtInfo()
      setTitle()
    })
  }, "p_form_unforeseeable_yf_m.phid_pc");
  // 监听合同编码的选择
  useValuesChange(({ args }) => {
    console.log(`合同编码监听信息`, args);
    setTimeout(() => {
      cntMFilter();
      getCntInfo();
      getZbdAmtByCnt()
      getFbyfAmtInfo()
      setTitle()
    }, 300);
  }, "p_form_unforeseeable_yf_m.u_main_cnt");

  useValuesChange(({ args }) => {
    getSuppyInfo()
  }, "p_form_unforeseeable_yf_m.u_payee")


  function getProjectInfo() {
    console.log(`项目phid_pc`, oneTable.getItem("phid_pc").getValue());
    $NG.execServer(
      "getPtInfoByPhid",
      { phid: oneTable.getItem("phid_pc").getValue() },
      (res) => {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(`项目jsonINfo`, datas);
        $NG.updateState((updater) => {
          updater.data.p_form_unforeseeable_yf_m.setProps({
            u_pc_no: datas.pc_no,
            u_division: {
              value: datas.division_phid,
              label: datas.division_name,
            },
            u_regional_center: {
              value: datas.regional_center_phid,
              label: datas.regional_center_name,
            },
            u_product_line: {
              //产品线
              value: datas.midwife_phid,
              label: datas.midwife_name,
            },
          });
        });
      }
    );
  }

  //合同根据项目ID过滤
  function cntMFilter() {
    $NG.updateUI((updater, state) => {
      console.log("过滤参数检查", updater);
      updater.fieldSetForm.p_form_unforeseeable_yf_m.u_main_cnt.setProps({
        onBeforeOpen: async () => {
          var phid_pc = $NG.getCmpApi("p_form_unforeseeable_yf_m").getItem("phid_pc").getValue();
          if (!phid_pc) {
            $NG.alert("请先选择项目");
            return false;
          } else {
            return true;
          }
        },
        ...(!!$NG.getCmpApi("p_form_unforeseeable_yf_m").getItem("phid_pc").getValue() && {
          clientSqlFilter: {
            'phid_pc': $NG.getCmpApi("p_form_unforeseeable_yf_m").getItem("phid_pc").getValue(),
          },
        }),
      });
    });
  }

  function getCntInfo() {
    console.log(`合同id`, oneTable.getItem("u_main_cnt").getValue());
    if (!oneTable.getItem("u_main_cnt").getValue()) return;
    $NG.execServer(
      "unforeseeable_fb_info",
      { phid: oneTable.getItem("u_main_cnt").getValue() },
      (res) => {
        console.log(res);
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log("通过合同id获取的信息", datas);
        $NG.updateState((updater) => {
          updater.data.p_form_unforeseeable_yf_m.setProps({
            u_main_cnt_no: datas.u_cnt_no,
            u_fbht_amt: datas.u_amt_vat,
            u_supply: {
              label: datas.yf_name,
              value: datas.yf_id,
            },

            u_payee: {
              label: datas.yf_name,
              value: datas.yf_id,
            },
            u_pay_org: {
              label: datas.jf_name,
              value: datas.jf_id
            },
          });
        });
        // 延迟获取供应商信息
        setTimeout(() => {
          getSuppyInfo()
        }, 300)
      }
    );
  }

      useDataIndexChange(({ args }) => {
        const record = args[0];
        record.u_hd_amt =record.u_bq_apply_je;
        dgir1.updateRow(args[0]);

      }, "u_bq_apply_je");


  let __timeId = 0;
  useUpdateRows(({ args }) => {
    console.log("更新数据1", args[0])
    if (__timeId) {
      clearTimeout(__timeId);
    }
    __timeId = setTimeout(() => {
      const total_amt = 0
      args[0].forEach((item) => {
       
        if ((Number(item.u_bq_apply_je) || 0) > ((Number(oneTable.getItem('u_fbht_amt').getValue()) || 0-(Number(oneTable.getItem('u_fbhtyfk').getValue()) || 0)))) {
          $NG.alert(`本期申请金额不得大于剩余金额，请重新填写！`)
          item.u_bq_apply_je = 0
        }
      });

      dgir1.refreshView();
    }, 200);
  }, "p_form_unforeseeable_yf_d1");

  //监听发票信息表
  useUpdateRows(({ args }) => {
    console.log("更新数据2", args[0]);
    reduceTable2(args[0]);
    dgir2.refreshView();
  }, "p_form_unforeseeable_yf_d2");
  function reduceTable2(rows) {
    // 发票金额
    let u_amt = 0;
    // 税额
    let u_tax_amt = 0;
    // 价税合计
    let u_amt_vat_total = 0;
    rows.forEach((item, index) => {
      u_amt += item.u_amt_vat_total ? item.u_amt_vat_total : 0;
      u_tax_amt += item.u_total_tax_amt ? item.u_total_tax_amt : 0;
    });
    $NG.updateState((updater) => {
      updater.data.p_form_unforeseeable_yf_m.setProps({
        u_bckpje: u_amt,
        u_yksje: u_tax_amt,
      });
    });
  }
  //监听付款信息表
  useUpdateRows(({ args }) => {
    console.log("更新数据1", args[0]);
    reduceTable1(args[0]);

    dgir1.refreshView();
  }, "p_form_unforeseeable_yf_d1");
  function reduceTable1(rows) {

    // 申请金额
    let u_bq_apply_je = 0;
    let hd_total_amt = 0
    rows.forEach((item, index) => {
      if (!item.u_bz) {
        item.u_bz = 1;
        item.u_bz_EXName = "人民币";
      }
      u_bq_apply_je += (Number(item.u_bq_apply_je) || 0)
      hd_total_amt += (Number(item.u_hd_amt) || 0)
    });
    $NG.updateState((updater) => {
      updater.data.p_form_unforeseeable_yf_m.setProps({
        u_bcsqfkje: u_bq_apply_je,
        u_hdzf_amt: hd_total_amt
      });
    });

  }

  // 计算2个日期之间得天数
  function formatDate(dateStr, outputFormat) {
    const date = new Date(dateStr);

    if (isNaN(date)) {
      return "无效的日期字符串";
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");

    let formattedDate;

    switch (outputFormat) {
      case "yyyy-mm-dd":
        formattedDate = `${year}-${month}-${day}`;
        break;
      case "yyyy-mm-dd HH:mm":
        formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
        break;
      // 可以根据需要继续添加其他格式的处理逻辑
      default:
        formattedDate = "不支持的输出格式";
    }

    return formattedDate;
  }
  var tabPanel = document.getElementsByClassName("ant-tabs-tab"); //获取所有tab页元素
  tabPanel[1].addEventListener("click", function () {
    console.log("tab2被点击了");
    setTimeout(() => {
      if (page.oType == "add") {
        $NG.getCmpApi("toolbar_top").getItem("save").getRef().click(); //点击获取发票的时候，保存单据
        $NG.alert("请先保存主表数据");
        tabPanel[0].click();
      }
    }, 200);
  });

  // getZbdAmtByCnt()
  function getZbdAmtByCnt() {
    const cnt = mstform.getItem("u_main_cnt").getValue();
    if (!cnt) return
    $NG.execServer("Getunforeseeable", { cnt: cnt }, (res) => {
      if (res.count == 0) return
      const _data = JSON.parse(res.data)[0].extendObjects
      $NG.updateState((updater) => {
        updater.data.p_form_unforeseeable_yf_m.setProps({
          u_fbhtyfk: (Number(_data.amt) || 0)
        })

      })
    })
  }

  // 获取分包应付单相应累计金额
  //getFbyfAmtInfo()
  function getFbyfAmtInfo() {
    const cnt = mstform.getItem("u_main_cnt").getValue();
    if (!cnt) return
    $NG.execServer("Getunforeseeable", { cnt: cnt }, (res) => {
      console.log(`累计金额`, res);
      if (res.count == 0) return
      const _data = JSON.parse(res.data)[0].extendObjects
      $NG.updateState((updater) => {
        updater.data.p_form_unforeseeable_yf_m.setProps({
          u_fbljkpje: (Number(_data.kpamt) || 0),
          u_main_cnt_ykpje: _data.sqamt
        })
      })
    })
  }

  // 获取供应商银行信息
  function getSuppyInfo() {
    const phid = mstform.getItem("u_payee").getValue()
    if (!phid) return
    $NG.execServer("GetFbCntBankInfo", { phid }, (res) => {
      console.log(`查询供应商信息`, res);
      if (res.count == 0) return
      const _data = JSON.parse(res.data)[0].extendObjects
      $NG.updateState((updater) => {
        updater.data.p_form_unforeseeable_yf_m.setProps({
          u_bank_no: _data.u_yfzh,
          u_rece_bank: {
            label: _data.bankname,
            value: _data.bphid
          }
        })
      })
    })
  }

});

//获取合同数量
function getCntCount(table, key, fun) {
  if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
  $NG.execServer("getUnforesseable_cnt_sl", { phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
    switch (res.count) {
      case 0:
        return;
      case 1:
        const datas = JSON.parse(res.data)[0].extendObjects;
        const temp_map = {};
        temp_map[key] = datas.phid;
        temp_map[`${key}_EXName`] = datas.bill_name;
        $NG.updateState((updater) => {
          updater.data[table].setProps({
            ...temp_map,
          });
          setTimeout(() => {
            if (fun) {
              fun();
            }
          }, 200);
        });
    }
  });
}
